<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use ZipStream\Option\Method;

/**
 * 预检录入
 *
 * @icon fa fa-circle-o
 */
class Detection extends Backend
{

    protected $noNeedLogin=[];
    protected $noNeedRight = [];
    /**
     * Detection模型对象
     * @var \app\admin\model\Detection
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Detection;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as &$row) {
                $detection_json = json_decode($row['detection_json'],'true');
                $row->sample_name = empty($detection_json) ? '' : $detection_json[0]['sample_name'];
                $row->getRelation('unit')->visible(['id','name','address','producer','phone']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        if (false === $this->request->isPost()) {
            $code = md5(time());
            $this->view->assign("code", $code);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $this->modelValidate = true;
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $unit_id = $params['unit_id'];
            $res = $this->model->where(['token'=>$params['token']])->find();
            if($res){
                $this->success('','/adminweb.php/detection/add');
            }
            $unitModel = new \app\admin\model\Unit();
            $unit = $unitModel->where(['id'=>$unit_id])->find();
            if(empty($unit)){
                $this->error("受检方未录入");
            }
            $startime = strtotime(date("Y-m-d 00:00:00"));
            $endtime = strtotime(date("Y-m-d 23:59:59"));
            $num = $this->model->where("create_time > $startime and create_time < $endtime")->sum('num');
            $arr = json_decode($params['detection_json'],'true');
            if(empty($arr)){
                $this->error("请输入检测结果定性");
            }
            $params['num'] = count($arr);
            $params['old_num'] = count($arr);
            $params['unit_name'] = $unit['name'];
            $params['phone'] = $unit['phone'];
            $params['name'] = $unit['producer'];
            $params['address'] = $unit['address'];
            $params['create_id'] = $this->auth->id;
            $params['create_nickname'] = Admin::where(['id'=>$this->auth->id])->value('nickname');
            $reagentModel = new \app\admin\model\Reagent();
            $projectModel = new \app\admin\model\Project();
            $menthodModel = new \app\admin\model\Menthod();
            $reagentLogModel = new \app\admin\model\ReagentLog();
            $resultModel = new \app\admin\model\Result();

            foreach ($arr as $k => &$v) {
                if(empty($v['name'])){
                    $this->error("请输入 ".$v['sample_name']." 试剂编码");
                }
                $reagent = $reagentModel->where(['id'=>$v['name']])->find();
                if($reagent['num'] <=0){
                    Db::rollback();
                    $this->error($reagent['name']." 试剂无可用数量");
                }
                $insertLog = [
                    'type'=>2,
                    'name'=>$reagent['name'],
                    'unit_name'=>$unit['name'],
                    'sample_name' => $v['sample_name'],
                    'item_name'=> $projectModel->where(['id'=>$v['project']])->value('name'),
                    'method'=>$menthodModel->where(['id'=>$v['method']])->value('name'),
                    'create_time'=>time(),
                    'sample_code'=>$reagent['code'],
                    'admin_name'=>Admin::where(['id'=>$this->auth->id])->value('nickname'),
                    'remark'=>"正常使用出库，使用数量 1"
                ];
                $reagentModel->where(['id'=>$v['name']])->dec('num')->update();
                $reagentLogModel->insert($insertLog);
                $num++;
                $v['code'] ='SNA'. str_pad($unit['id'], 4, '0', STR_PAD_LEFT).date('md').$num;
                $v['outmsg'] =$reagent['outmsg'];
                $v['unitmsg'] =$reagent['unitmsg'];
                $v['result']= $resultModel->where(['id'=>$v['resultid']])->value('name');
            }
            $monthstarttime =  strtotime(date("Y-m-01 00:00:00"));
            $monthendtime  = strtotime(date("Y-m-31 23:59:59"));
            $monthnum = $this->model->where("create_time > $monthstarttime and create_time < $monthendtime")->count();
            $params['code'] = 'JR'.$unit['pinyin'] . date('Ym').$monthnum;
            $params['detection_json'] = json_encode($arr,JSON_UNESCAPED_UNICODE);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }

        $this->success('','/adminweb.php/detection/add');
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $unit_id = $params['unit_id'];
            $unitModel = new \app\admin\model\Unit();
            $unit = $unitModel->where(['id'=>$unit_id])->find();
            if(empty($unit)){
                $this->error("受检方未录入");
            }
            $olddetectionjson =json_decode($row['detection_json'],'true');
            $startime = strtotime(date("Y-m-d 00:00:00"));
            $endtime = strtotime(date("Y-m-d 23:59:59"));
            $num = $this->model->where("create_time > $startime and create_time < $endtime")->sum('num');
            $arr = json_decode($params['detection_json'],'true');
            $params['num'] = count($arr);
            $params['unit_name'] = $unit['name'];
            $params['phone'] = $unit['phone'];
            $params['name'] = $unit['producer'];
            $params['address'] = $unit['address'];
            $reagentModel = new \app\admin\model\Reagent();
            $projectModel = new \app\admin\model\Project();
            $menthodModel = new \app\admin\model\Menthod();
            $reagentLogModel = new \app\admin\model\ReagentLog();
            $resultModel = new \app\admin\model\Result();
            foreach ($arr as $k => &$v) {
                $reagent = $reagentModel->where(['id'=>$v['name']])->find();
                if((!empty($olddetectionjson[$k]) && $v['name'] != $olddetectionjson[$k]['name']) || empty($olddetectionjson[$k])){
                    if($reagent['num'] <=0){
                        Db::rollback();
                        $this->error($reagent['name']." 试剂无可用数量");
                    }
                    $insertLog = [
                        'type'=>2,
                        'name'=>$reagent['name'],
                        'unit_name'=>$unit['name'],
                        'sample_name' => $v['sample_name'],
                        'item_name'=> $projectModel->where(['id'=>$v['project']])->value('name'),
                        'method'=>$menthodModel->where(['id'=>$v['method']])->value('name'),
                        'remark'=>"正常使用出库，使用数量 1"
                    ];
                    $reagentModel->where(['id'=>$v['name']])->dec('num')->update();
                    $reagentLogModel->insert($insertLog);
                }
                $num++;
                if(empty($v['code'])){
                    $v['code'] ='SNA'. str_pad($unit['id'], 4, '0', STR_PAD_LEFT).date('md').$num;
                }
                $v['outmsg'] =$reagent['outmsg'];
                $v['unitmsg'] =$reagent['unitmsg'];
                $v['result']= $resultModel->where(['id'=>$v['resultid']])->value('name');
            }
            if(empty($row['code'])){
                $monthstarttime =  strtotime(date("Y-m-01 00:00:00"));
                $monthendtime  = strtotime(date("Y-m-31 23:59:59"));
                $monthnum = $this->model->where("create_time > $monthstarttime and create_time < $monthendtime")->count();
                $params['code'] = 'JR'.$unit['pinyin'] . date('Ym').$monthnum;
            }

            $params['detection_json'] = json_encode($arr,JSON_UNESCAPED_UNICODE);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
